package com.yjps.system.service;


import com.yjps.common.page.Pager;
import com.yjps.system.dao.ComplaintDao;
import com.yjps.system.model.Complaint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jessy on 2015/8/25.
 */
@Service
public class ComplaintService {
    Logger log = LoggerFactory.getLogger(ComplaintService.class);

    @Autowired
    ComplaintDao complaintDao;

    public Complaint getComplaint(int id){
        return complaintDao.load(id);
    }

    public int addComplaint(Complaint complaint){
        return complaintDao.save(complaint);
    }


    public Pager<Complaint> getComplaintByPagerWithKey(Pager<Complaint> pager,String acceptResult) throws Exception {
        Map<String, Object> params = new HashMap<>();
        String queryString = "from Complaint t where t.isValid = 1";
        if(!StringUtils.isEmpty(acceptResult)) {
            queryString += " and t.acceptResult =:acceptResult";
            params.put("acceptResult", Integer.parseInt(acceptResult));
        }
        queryString += " order by t.id desc";
        List<Complaint> accounts = complaintDao.findWithSelect(queryString, params, (pager.getPageNo()-1)*pager.getPageSize(), pager.getPageSize());
        pager.setCount(complaintDao.getTotalCount(queryString, params));
        pager.setList(accounts);
        return pager;
    }

    public void updateComplaint(Complaint complaint){
        String hql = "update Complaint c set c.complaintState =:complaintState,c.complaintReason =:complaintReason,c.acceptResult =:acceptResult,c.acceptTime = :acceptTime where c.id =:id";
        Map<String, Object> map = new HashMap<>();
        map.put("complaintState",complaint.getComplaintState());
        map.put("complaintReason",complaint.getComplaintReason());
        map.put("acceptResult",complaint.getAcceptResult());
        map.put("acceptTime",complaint.getAcceptTime());
        map.put("id",complaint.getId());
        complaintDao.excute(hql, map);
    }

    /**
     * 删除（使无效）一条投诉记录
     * @param id
     */
    public void deleteComlaint(int id){
        complaintDao.invalid(getComplaint(id));
    }
}
